home *** CD-ROM | disk | FTP | other *** search
/ Ian & Stuart's Australian Mac 1993 September / September 93.iso / Archives / Mac FAQ / Mac PD Programmer.FAQ < prev    next >
Text File  |  1993-10-10  |  56KB  |  1,436 lines

  1. Archive-name: macintosh/programming-faq
  2.  
  3. The Public Domain Mac Programming FAQ Answer sheet.
  4. Last update: 930922
  5.  
  6. This sheet was started by and is presently maintained by Jon 
  7. W{tte, whom you may reach as h+@nada.kth.se. If there is 
  8. anything you find errant, missing or in need of an update, 
  9. please send me your submission and I will include it (I can't 
  10. promise correct attributions, but I will try) All FAQ Answer 
  11. submissions sent to me will be considered to be in the public 
  12. domain unless stated otherwise (in which case they will not be 
  13. included in this FAQ sheet)
  14.  
  15. This sheet is currently archived on nada.kth.se where you can 
  16. reach it using afs as /afs/nada.kth.se/public/ftp/pub/hacks/mac-f
  17. aq/CSMP_PD_FAQ or using anonymous FTP (GIVE YOUR E-MAIL ADDRESS 
  18. AS PASSWORD!) as pub/hacks/mac-faq/CSMP_PD_FAQ
  19.  
  20. I will try to update this sheet every three weeks or so. Changes 
  21. since last revision:
  22.  
  23. Fixed spelling and formatting. Added question numbering.
  24.  
  25. Files and Networks: [Mattias Ullrich]
  26.  
  27. Lisp and SmallTalk: [Rainer Joswig]
  28.  
  29. Free development languages: [Bob Loewenstein]
  30.  
  31. Various: [Pete Gontier]
  32.  
  33. Lots of suggestions: [Peter Lewis]
  34.  
  35. Wake Up And Smell The Glue: [Matthias Neeracher]
  36.  
  37. This sheet is divided into several parts; each of which covers a 
  38. general area which often gets asked about in the Internet 
  39. newsgroup comp.sys.mac.programmer. Please download a copy of 
  40. this answer sheet and search it before you post to the 'net, to 
  41. help reduce bandwidth.
  42.  
  43. There is NO or VERY LIMITED error checking in these code 
  44. examples, FOR BREVITY ONLY. You should make sure you ALWAYS 
  45. check ALL return codes, and handle any that you are not prepared 
  46. to deal with appropriately.
  47.  
  48. The groups are (you may search for *<number>* to jump directly 
  49. to a group with its questions and answers)
  50.  
  51. 0) Development and debugging tools and documentation for the Mac
  52.  
  53. 1) Files and the File Manager
  54.  
  55. 2) Serial ports
  56.  
  57. 3) TCP/IP and sockets
  58.  
  59. 4) AppleEvents and the Apple Object Model
  60.  
  61. 5) AppleScript
  62.  
  63. 6) Drawing using QuickDraw
  64.  
  65. 7) Drawing NOT using QuickDraw (aka directly to screen)
  66.  
  67. 8) Cache issues and other processor differences
  68.  
  69. 9) What about pre-emptive multitasking?
  70.  
  71. 10) Handles; they are driving me crazy; Memory issues
  72.  
  73. 11) _Gestalt and compatibility
  74.  
  75. 12) Standalone code and dynamic linking
  76.  
  77. 13) Reading the keyboard for games and screen savers
  78.  
  79. 14) QuickTime
  80.  
  81. 15) Ice Cream and Frozen Yoghurt
  82.  
  83. *0* Development and debugging tools for the Macintosh
  84.  
  85. 0.1) Q: What do I need to start writing Macintosh software? 
  86.  
  87. A: A Mac, a lot of time, and a few hundred $. Although you can 
  88. develop software on a Classic-type machine, it is not to be 
  89. attempted by the weak of heart or stressed of time. If you're 
  90. doing paid work and/or work for a company, a Quadra-class 
  91. machine or Centris 650 or better is almost a must; remember that 
  92. your time costs your employer much more than just your salary. 8 
  93. MB is a minimum to run at all comfortably, and Virtual Memory is 
  94. not suited for development work. Similarly; if you don't have at 
  95. least 20 MB free on your hard disk (40 MB for MPW) you need to 
  96. buy more space.
  97.  
  98. You need a development system such as Think C, Think Pascal , 
  99. MPW C or Prograph, you need at least some of the New Inside Mac 
  100. books (Toolbox Essentials, Files, Memory come to mind) and a 
  101. good entry-level third-party book may help.
  102.  
  103. Once you are up to speed on the general layout of the Mac and 
  104. its toolboxes, you should call APDA and order the monthly 
  105. developer mailing, which will give you a CD chock full of 
  106. documentation, utilities and system software once a month. You 
  107. will also, obviously, need a CD player; one of which Apple's own 
  108. CD300 is a very good buy at the time of writing this.
  109.  
  110. Another tool which many find a must-have is the Think Reference 
  111. version 2.0, containing reference material on the most used 
  112. parts of the Mac toolbox with lightning-fast look-up and mostly 
  113. correct usage hints and code snippets.
  114.  
  115. 0.2) Q: What is the most used Macintosh development language?
  116.  
  117. A: Out of products on the market, I have no idea; both MPW and 
  118. Think products appear to be used. Among hobbyists, the Think 
  119. products from Symantec are most popular because of the low 
  120. price, and steep educatinoal discounts, and, of course, the 
  121. easily approachable interface!
  122.  
  123. The Think C linker only strips dead code on a FILE level basis 
  124. (and this is when you turn on "Smart Linking") The MPW linker 
  125. (of no specified IQ, as someone so eloquently put it :-) strips 
  126. dead code by the function. That may be part of the reason the 
  127. Think C linker is ten times faster than the MPW linker.
  128.  
  129. In the beginning, the Mac was programmed using Mc68000 assembly 
  130. or Pascal; this was reflected in the Old Inside Mac volumes 
  131. which only gave pascal-style and assembly-style interfaces to 
  132. the Mac toolbox. These days, Apple tells us to use C or even 
  133. better C++ for developing new applications, as that will speed 
  134. up the transition to PowerPC and also coming cross-platform 
  135. efforts.
  136.  
  137. There are also at least two Fortran compilers, at least three 
  138. SmallTalk implementations (ObjectWorks, SmallTalk/V and 
  139. SmallTalkAgents), a world-class LISP/CLOS implementation 
  140. (Macintosh Common Lisp 2.0) and a Modula/2 implementation.
  141.  
  142. There is another good Common Lisp implementation: Procyon Common 
  143. Lisp. Years ago we had a version. I don't know if it is actively 
  144. supported. But Procyon CL is also available for DOS, OS/2 and 
  145. Windows (as Allegro CL/PC) and actively developed.
  146.  
  147. 0.3) Q: Where do I find a public domain C compiler for the Mac. 
  148. Is there a GCC for the mac? What about the FSF boycott of Apple 
  149. products?
  150.  
  151. A: There is no really good solution for a "for-free" C 
  152. development system for the Mac. GCC has been ported, but 
  153. requires the MPW shell and MPW assembler to run; these have to 
  154. be bought from APDA. There was a freely available C compiler 
  155. called Harvest C, which was somewhat unstable but usable for 
  156. smaller programs; it was abandoned by the original author Eric W 
  157. Sink because of a lack of time, and sort-of maybe kind-a-taken 
  158. over by the TopSoft organization, after which it hasn't 
  159. re-surfaced.
  160.  
  161. The FSF boycott of Apple products means they will not talk to 
  162. you if you ask them for help in doing a Mac port, and they will 
  163. not incorporate your changes into their main code base. However, 
  164. they still allow others to port GNU stuff to the Mac, and it has 
  165. been done with most of the application-like GNU programs (bison, 
  166. flex, perl, ...)
  167.  
  168. 0.4) Q: Are there any other free Mac development platforms?
  169.  
  170. A: Yerk and Mops. These are object oriented languages based on 
  171. the old product Neon which itself was based on Forth. They are 
  172. available with Manuals at oddjob.uchicago.edu (anonymous FTP).
  173.  
  174. 0.5) Q: What's the difference between the MPW and Think 
  175. environments?
  176.  
  177. A: The main difference is that Think is an integrated 
  178. environment, while MPW provides you with a command-line shell 
  179. for your Mac and tools to use in it. MPW also has a slightly 
  180. higher systems demand and a much slower linker.
  181.  
  182. The good thing about MPW is that you can write scripts and make 
  183. files to do anything you want in the way you want it. Think 
  184. still doesn't have a viable solution to do a build that requires 
  185. more than one link operation, or has more than one destination 
  186. file.
  187.  
  188. For the MPW environment, there are three source level debuggers; 
  189. SADE, SourceBug and Voodoo Monkey. The latter is an experimental 
  190. debugger with support for threads debugging; the middle is 
  191. bundled with MPW while SADE has to be bought separately (but is 
  192. fully scriptable in its own scripting language)
  193.  
  194. The Think environments have their own integrated debuggers; the 
  195. Think Pascal one has a lot of useful features while the Think 
  196. C/C++ one is a little more basic (but is gaining in 
  197. functionality with each release) Stepping through source code 
  198. and looking at variables is generally faster and easier in Think 
  199. than the MPW debuggers.
  200.  
  201. Any commercial Mac developer should have both Think and MPW of 
  202. whatever language they prefer (Pascal, C or C++)
  203.  
  204. 0.6) Q: What is a good low-level debugger for the Mac?
  205.  
  206. A: MacsBug is freely available for ftp from ftp.apple.com; log 
  207. in as user anonymous and give your FULL e-mail address as 
  208. password. MacsBug is your basic monitor-type debugger that takes 
  209. a few hundred Ks of memory, and lets you break, step, 
  210. disassemble, look at the stack etc of most anything running on 
  211. your Mac. Since it's free (it's also on the developer CDs) and 
  212. provides most of the functionality you need, this is a popular 
  213. choice.
  214.  
  215. TMON is another debugger which sports a more mac-like interface; 
  216. it provides windows and uses the mouse. It can take as little or 
  217. much memory as you want by excluding or including certain areas 
  218. of functinoality. A nice touch is the 6502 disassembler that you 
  219. can use to de-bug the code the IOP processors run on the Mac 
  220. IIfx and Quadra 900/950.
  221.  
  222. Jasik Designs have a debugger called The Debugger which can do 
  223. both low- and high-level debugging, with or without source and 
  224. for all types of code, application, code resources, everything. 
  225. This is the debugger of choise for many large developers because 
  226. of its high power and many features not found anywhere else. 
  227. However; newcomers beware! This is the Lamborghini of debuggers; 
  228. if you know how to drive it it is the fastest way from A to B; 
  229. if you don't, you'll just end up in the ditch.
  230.  
  231. 0.7) Q: Are there any visual developments environments for the 
  232. Mac (comparable to Visual C++)
  233.  
  234. A: There is no Visual C++ as such. However, there is a C++ 
  235. parser/editor called ObjectMaster which provides good browsing 
  236. and editting capabilities if you already have a C++ compiler. 
  237. Think C++ also comes with a browser built-in, and you can draw 
  238. dialogs/windows using plain old ResEdit, even for your custom 
  239. view types.
  240.  
  241. There is a fully visual, dynamic, object oriented data-flow-drive
  242.  n programming language for the Mac called Prograph Corporate 
  243. Programming Something-or-other (CPX). It is expensive ($1500) 
  244. but offers a built-in database, easy interfaces to existing data 
  245. bases, very high productivity in implement-test-debug cycling 
  246. and also offers cross-platform capabilities (it comes with a 
  247. class library which, when your code is written using it, works 
  248. under Windows after re-compilation)
  249.  
  250. There is a crossing between SmallTalk and C++ that is called 
  251. Component Workshop; although it seems large and slowly evolving, 
  252. it does offer some promising features not found in C++ itself.
  253.  
  254. There is also something called SmalltalkAgents that makes it 
  255. easy to create Mac applications using ParcPlace Smalltalk. If 
  256. you'd rather do Common Lisp, Macintosh Common Lisp offers a 
  257. Common Lisp Object System with support for most Mac interface 
  258. items; you can edit code while it is running and build 
  259. stand-alone applications.
  260.  
  261. However, all of these tools generate rather larger binaries with 
  262. larger system demands than a program written in C. On the other 
  263. hand; C++ programs require more memory and disk space than 
  264. programs written in assembly. It's a trade-off, and I beliece 
  265. this type of tools is the wave of the near future.
  266.  
  267. 0.8) Q: What class libraries are there for the Mac?
  268.  
  269. A: Apart from the libraries mentioned above, there are three 
  270. contenders: MacApp, TCL, and OOPC. On the horizon may be 
  271. Bedrock.
  272.  
  273. MacApp is a heavy-duty class library that has tons of features 
  274. and a steep learning curve; it runs under MPW with Pascal or 
  275. C++, and also under Think Pascal 4.0 A major application written 
  276. in MacApp is PhotoShop.
  277.  
  278. TCL stands for Think Class Library and comes with Think Pascal, 
  279. C or C++. It is a smaller library that still fills most peoples 
  280. needs; since Think C implements a subset of C++ (the most 
  281. important OO concepts such as virtual functions and inheritance) 
  282. and the TCL is carefully written not to take advantage of any 
  283. C++ features not in Think C, you can use it with Think C. A 
  284. major application written in TCL is Lotus 1-2-3.
  285.  
  286. OOPC is a newcomer in the field, and uses plain ANSI C. However, 
  287. it mangles the pre-processor to provide you with a system with 
  288. full inheritance, virtual functions, and dynamic re-binding of 
  289. functions for classes or individual objects. Startup is slow, 
  290. since all "linking" of virtual functions and classes is made at 
  291. run-time, but performance otherwise is good. A Windows version 
  292. is promised for later this year.
  293.  
  294. 0.9) Q: How should I debug and test my software?
  295.  
  296. A: Get ahold of, and install, the extensions DoubleTrouble, 
  297. DisposeResource and MrEvenBetterBusError. They will catch 80% of 
  298. any memory related bugs you may have, including many bugs that 
  299. follow NULL handles or pointers.
  300.  
  301. A low-level debugger is required, and while you install it, 
  302. install the "leaks" dcmd which will help you catch memory leaks 
  303. in your application. All of these tools are available from 
  304. ftp.apple.com.
  305.  
  306. *1* Files and the File Manager
  307.  
  308. 1.1) Q: How do I tell fopen() to open a file the user has 
  309. selected using StandardGetFile?
  310.  
  311. A: The "standard" ANSI C file functions are less than well 
  312. suited for the Macintosh way of doing things. However, if you 
  313. are doing a port for your own enjoyment and benefit (or maybe 
  314. for in-house work) you can use the following function: (see 
  315. below abbout converting a wdRefNum into a vRefNum/parID pair)
  316.  
  317. *code*
  318. FILE *
  319. fopen_mac ( short vRefNum , long parID , char * fileName , char * mode ) {
  320. short oldVol ;
  321. short aVol ;
  322. long aDir , aProc ;
  323. FILE * ret = NULL ;
  324.     if ( GetVol ( NULL , & oldVol ) ) {
  325.         return NULL ;
  326.     }
  327. if ( GetWDInfo ( oldVol , & aVol , & aDir , & aProc ) ) { return NULL  ;
  328.     }
  329.     if ( HSetVol ( NULL , vRefNum , parID ) ) {
  330.         return NULL ;
  331.     }
  332.     ret = fopen ( fileName , mode ) ;
  333.     if ( HSetVol ( aVol , aDir ) ) {
  334.         /* an error we can't currently handle */
  335.     }
  336.     if ( SetVol ( oldVol ) ) {
  337.         /* an error we can't currently handle */
  338.     }
  339.     return ret ;
  340. }
  341. *end*
  342.  
  343. All of the above is necessary for one reason or another - if you 
  344. are interested, by all means look HSetVol up in Think Reference 
  345. 2.0 or New Inside Mac: Files.
  346.  
  347. In older versions of MPW; this wouldn't work since the MPW 
  348. libraries used to do a GetVol and explicitly use that value by 
  349. itself.
  350.  
  351. 1.2) Q: When can I use the HOpen, HCreate etc file calls? Are 
  352. they only System 7 calls?
  353.  
  354. A: All the HXxx calls that take a vRefNum and parID as well as 
  355. the file name are implemented in glue that works on any system 
  356. that has HFS (meaning 3.2 and up with the HD20 INIT, and all 
  357. systems from System 6 and up)
  358.  
  359. The glue is available in MPW 3.2 and up, and Think C 5.0 and up.
  360.  
  361. This goes for all HXxx calls except HOpenDF; therefore, if you 
  362. are interested in System 6 compatibility, use HOpen instead and 
  363. make sure you don't allow file names beginning with a period.
  364.  
  365. 1.3) Q: Why do you say wdRefNum sometimes and vRefNum sometimes? 
  366. Why do you say parID sometimes and dirID sometimes?
  367.  
  368. A: When the Mac first made an appearance in 1984, it identified 
  369. files by using a vRefNum (volume reference numbear meaning a 
  370. floppy disk or later hard disk) and a name. Once HFS saw the 
  371. light of day, folders within folders became a reality, and you 
  372. needed a dirID as well to point out what folder you really meant 
  373. on the volume. However, older programs that wasn't being 
  374. rewritten still knew nothing about directory IDs, so Apple had 
  375. SFGetFile make up "fake" vRefNums that didn't just specify a 
  376.  
  377. volume, but also a parent folder. These are called wdRefNums 
  378. (for working directory) and were a necessary evil invented in 
  379. 1985. You should not create (or, indeed, use) wdRefNums 
  380. yourself.
  381.  
  382. There is a system-wide table that maps wdRefNums onto 
  383. vRefNum/parID pairs. There is a limit to the size of this table.
  384.  
  385. A dirID and a parID is almost the same thing; you say "parID" 
  386. when you mean the folder something is in, while you say a 
  387. "dirID" when you mean the folder itself. If you for instance 
  388. have a fodler called "Foo" with a folder called "Bar" in it, the 
  389. parID for "Bar" would be the dirID for "Foo."
  390.  
  391. 1.4) Q: How do I convert a wdRefNum as returned by SFGetFile 
  392. into a vRefNum/parID pair to use with the HXxx calls.
  393.  
  394. A: Use GetWDInfo, which is declared as:
  395.  
  396. pascal OSErr GetWDInfo ( short wdRefNum , short * vRefNum , long 
  397. * parID , OSType * procID ) ;
  398.  
  399. The procID parameter must be non-NULL and point to an OSType 
  400. variable, but the value of that variable can and should be 
  401. ignored.
  402.  
  403. It is recommended that, as soon as you get your hands on a 
  404. wdRefNum, for instance from SFGetFile, you directly convert it 
  405. into a vRefNum/parID pair and always use the latter to reference 
  406. the folder.
  407.  
  408. 1.5) Q: How do I select a folder using SFGetFile?
  409.  
  410. A: This requires a custom dialog with a filter proc. It is too 
  411. complicated to show here, but not totally impossible to 
  412. comprehend. There is sample code on ftp.apple.com, in the 
  413. directory dts/snippets, on how to do this.
  414.  
  415. 1.6) Q: How do I get the full path of a file referenced by a 
  416. vRefNum, parID and name?
  417.  
  418. A: You don't.
  419.  
  420. OK, I cheated you. There is exactly ONE valid reason to get the 
  421. full path of a file (or folder, for that matter) and that is to 
  422. display its location to the user in, say, a settings dialog. To 
  423. actually save the location of the file you should do this: 
  424. (assuming the file is in an FSSpec called theFile - you can use 
  425. FSSpecs in your program even if you don't run under System 7; 
  426. just make your own MyFSMakeFSSpec that fills in the FSSpec 
  427. manually if it's not implemented)
  428.  
  429. *code*
  430. if ( ! aliasManagerAvailable ) { /* System 6 ? */
  431. GetVolumeName ( theFile -> vRefNum , vName ) ; GetVolumeModDate ( vRefNum , & date ) ;
  432. Save ( vName , date , parID , fileName ) ;
  433. } else {
  434. NewAlias ( NULL , theFile , & theAlias ) ;
  435.     Save ( theAlias ) ;
  436.     DisposeHandle ( ( Handle ) theAlias ) ;
  437. }
  438. *end*
  439.  
  440. If you are really concerned about these issues (of course you 
  441. are!) you should save BOTH of these methods when available, and 
  442. load back whatever is there that you can handle; since users may 
  443. be using your application in a mixed System 6/System 7 
  444. environment.
  445.  
  446. To get back to the file is left as an excercise for the reader.
  447.  
  448. To open a file using fopen() or the Pascal equivalent, see above 
  449. about using and not using HSetVol.
  450.  
  451. 1.7) Q: What about actually getting the full path for a file? I 
  452. promise I will only use it to show the location of a file to the 
  453. user!
  454.  
  455. A: Enter PBGetCatInfo, the Vegimatic of the Mac file system. Any 
  456. Mac hacker of knowledge has taken this system call to his heart. 
  457. What you do is this:
  458.  
  459. *code*
  460. OSErr
  461. GetFolderParent ( FSSpec * fss , FSSpec * parent ) {
  462. CInfoPBRec rec ;
  463. short err ;
  464.     * parent = * fss ;
  465.     rec . hFileInfo    . ioNamePtr = parent -> name ;
  466.     rec . hFileInfo    . ioVRefNum = parent -> vRefNum ;
  467.     rec . hFileInfo    . ioDirID = parent -> parID ;
  468.     if ( parent -> name [ 0 ] ) {
  469.         rec . hFileInfo . ioFDirIndex = 0 ;
  470.     } else {
  471.         rec . hFileInfo . ioFDirIndex = -1 ;
  472.     }
  473.     rec . hFileInfo    . ioFVersNum = 0 ;
  474.     err = PBGetCatInfoSync ( & rec ) ;
  475. if ( ! ( rec . hFileInfo . ioFlAttrib & 0x10 ) ) { /* Not a folder */ if ( ! err ) {
  476.             err = dirNFErr ;
  477.         }
  478.     }
  479.     parent -> parID = rec . dirInfo . ioDrParID ;
  480.     parent -> name [ 0 ] = 0 ;
  481.     return err ;
  482. }
  483. OSErr
  484. GetFullPathHandle ( FSSpec * fss , Handle * h )
  485. {
  486.     Handle  tempH = NULL ;
  487.     short err ;
  488.     FSSpec fs = * fss ;
  489.     while ( fs . parID > 1 ) {
  490.         tempH = NULL ;
  491. PtrToHand ( & fs . name [ 1 ] , & tempH , fs . name [ 0 ] ) ; PtrAndHand ( ( void * ) ":" , tempH , 1 ) ;
  492.         HandAndHand ( * h , tempH ) ;
  493. SetHandleSize ( * h , 0L ) ; HandAndHand ( tempH , * h ) ; DisposeHandle ( tempH ) ; tempH = NULL ; 
  494. GetFolderParent ( & fs , & sSpec ) ;
  495.         fs = sSpec ;
  496.     }
  497.     GetVolName ( fs    . vRefNum , fs . name ) ;
  498. PtrToHand ( & fs . name [ 1 ] , & tempH , fs . name [ 0 ] ) ; PtrAndHand ( ( void * ) ":" , tempH , 1 ) ;
  499.     HandAndHand ( * h , tempH ) ;
  500.     SetHandleSize ( * h , 0L ) ;
  501.     HandAndHand ( tempH , * h ) ;
  502.     DisposeHandle ( tempH ) ;
  503.     tempH = NULL ;
  504.     if ( ! IsFolder ( fss ) ) {
  505.     SetHandleSize ( * h , GetHandleSize ( * h ) - 1 ) ; // Remove colon }
  506.     return 0 ;
  507. }
  508. *end*
  509.  
  510. 1.8) Q: So how do I get the names of the files in a directory?
  511.  
  512. A: You use PBGetCatInfo again, but this time you set ioFDirIndex 
  513. to 1 or more (you need to know the dirID and vRefNum of the 
  514.  
  515. folder you're interested in) You then call PBGetCatInfoSync for 
  516. values of ioFDirIndex from 1 and up, until you get an fnfErr. 
  517. Any other err means you are not allowed to get info about THAT 
  518. item, but you may be for the next. Then collect the names in the 
  519. string you made ioNamePtr point to as you go along. Note that 
  520. you need to fill in the ioDirID field for each iteration through 
  521. the loop, and preferrably clear the ioFVersNum as well.
  522.  
  523. Note that the contents of a directory may very well change while 
  524. you are iterating over it; this is most likely on a file server 
  525. that more than one user uses, or under System 7 where you run 
  526. Personal File Share.
  527.  
  528. 1.9) Q: How do I find the name of a folder for which I only know 
  529. the dirID and vRefNum?
  530.  
  531. A: You call (surprise!) PBGetCatInfo! Make ioNamePtr point to an 
  532. empty string (but NOT NULL) of length 63 (like, an Str63) and 
  533. ioFDirIndex negative (-1 is a given winner) - this makes 
  534. PBGetCatInfo return information about the vRefNum/dirID folder 
  535. instead of the file/folder specified by vRefNum, parID and name.
  536.  
  537. 1.10) Q: How do I make the Finder see a new file that I created? 
  538. Or if I changed the type of it; how do I display a new icon for 
  539. it?
  540.  
  541. A: You call (surprise!) PBGetCatInfo followed by PBSetCatInfo 
  542. for the FOLDER the file is in. Inbetween, you should set 
  543. ioDrMdDat to the current date&time. Code:
  544.  
  545. *code*
  546. OSErr
  547. TouchFolder ( short vRefNum , long parID ) {
  548. CInfoPBRec rec ;
  549. Str63 name ;
  550. short err ;
  551. rec . hFileInfo . ioNamePtr = name ; name [ 0 ] = 0 ;
  552. rec . hFileInfo . ioVRefNum = vRefNum ; rec . hFileInfo . ioDirID = parID ; rec . hFileInfo . ioFDirIndex = -1 ; rec . hFileInfo . ioFVersNum = 0 ; err = PBGetCatInfo ( & rec ) ;
  553.     if ( err ) {
  554. return err ;
  555.     }
  556. GetDateTime ( & rec . dirInfo . ioDrMdDat ) ; rec . hFileInfo . ioVRefNum = vRefNum ;
  557. rec . hFileInfo . ioDirID = parID ; rec . hFileInfo . ioFDirIndex = -1 ; rec . hFileInfo . ioFVersNum = 0 ;
  558.     err = PBSetCatInfo ( & rec ) ;
  559.     return err ;
  560. }
  561. *end*
  562.  
  563. 1.11) Q: Aren't we done with PBGetCatInfo soon?
  564.  
  565. A: Well, it turns out that you can also find out wether an 
  566. FSSpec is a file or a folder by calling PBGetCatInfo and check 
  567. bit 4 (0x10) of ioFlAttr to see wether it is a folder. You may 
  568. prefer to call ResolveAliasFile for this instead.
  569.  
  570. You can also check the script of the file's title using 
  571. PBGetCatInfo and check the ioFlFndrXInfo field if you want to 
  572. work with other script systems than the Roman system.
  573.  
  574. Another common use is to find out how many items are in a 
  575. folder; the modification date of something or the correct 
  576. capitalization of its name (since the Mac file system is case 
  577. independent BUT preserves the case the user uses)
  578.  
  579. 1.12) Q: How do I set what folder should initially be shown in 
  580. the SFGetFile boxes?
  581.  
  582. A: You stuff the dirID you want to show into the lo-mem global 
  583. CurDirStore, and the NEGATIVE of the vRefNum you want into the 
  584. lo-mem global SFSaveDisk.
  585.  
  586. If you are using StandardGetFile and return sfSelectionChanged 
  587. >from an "init" message handler, you must remember to clear the 
  588. script code, else the selection will not change.
  589.  
  590. *2* Serial ports
  591.  
  592. 2.1) Q: How do I get at the serial ports?
  593.  
  594. A: You call OpenDriver for the names "\p.AOut" and "\p.AIn" to 
  595. get at the modem port, and "\p.BOut" and "\p.BIn" for the 
  596. printer port. The function RAMSDOpen was designed for the 
  597. original Mac with 128 kB of memory and 64 kB of ROM, and has 
  598. been extinct for several years.
  599.  
  600. However, many users use their serial ports for MIDI, LocalTalk, 
  601. graphic tablets, or what have you and have installed an 
  602. additional serial port card to get more ports. What you SHOULD 
  603. do as a good application is to use the Comms Toolbox Resource 
  604. Manager to search for serial resources; this requires that the 
  605. Comms Toolbox is present (true on earlier System 6 with an INIT, 
  606. on later System 6 and System 7 always, as well as on A/UX) and 
  607. that you have initialized the comms resource manager. The exact 
  608. code follows (adapted from Inside Mac Comms Toolbox):
  609.  
  610. *code*
  611. #include <CommsResources.h>
  612. OSErr
  613. FindPorts ( Handle * portOutNames , Handle * portInNames , Handle * names , Handle * iconHandles ) {
  614. OSErr ret = noErr ;
  615. short old = 0 ;
  616. CRMRec theCRMRec , * found ; CRMSerialRecord * serial ;
  617. * portOutNames = NewHandle ( 0L ) ; * portInNames = NewHandle ( 0L ) ; * names = NewHandle ( 0L ) ;
  618. * iconHandles = NewHandle ( 0L ) ; while ( ! ret ) {
  619.         theCRMRec . crmDeviceType = crmSerialDevice ;
  620.         theCRMRec . crmDeviceID = old ;
  621.         found = ( CRMRec * ) CRMSearch ( ( QElementPtr ) & theCRMRec ) ;
  622.         if ( found ) {
  623.             serial = ( CRMSerailRec * ) found -> crmAttributes ;
  624.             old = found -> crm DeviceID ;
  625. PtrAndHand ( & serial -> outputDriverName , * portOutNames , sizeof ( serial -> outputDriverName ) ) ;
  626. PtrAndHand ( & serial -> inputDriverName , * portInNames , sizeof ( serial -> inputDriverName ) ) ;
  627.             PtrAndHand ( & serial -> name , * names , 
  628.                 sizeof ( serial -> name ) ) ;
  629. PtrAndHand ( & serial -> deviceIcon , * iconHandles , sizeof ( serial -> deviceIcon ) ) ;
  630.         } else {
  631.             break ;
  632.         }
  633.     }
  634.     return err ;
  635. }
  636. *end*
  637.  
  638. This will create four handles with the driver names, device 
  639. names and driver icon handles for all of the available serial 
  640. devices. Then let the user choose with a pop-up menu or 
  641. scrolling list, and save the choice in your settings file.
  642.  
  643. You can use OpenDriver, SetReset, SetHShake, SetSetBuf, 
  644. SerGetBuf and the other Serial Manager functions on these 
  645. drivers. To write to the serial port, use FSWrite for 
  646. synchronous writes that wait until all is written, or PBWrite 
  647. asynchronously for queuing up data that is supposed to go out 
  648. but you don't want to wait for it. At least once each tim
  649.  
  650. e through your event loop, you should call SerGetBuf on the in 
  651. driver reference number you got from OpenDriver, and call FSRead 
  652. for that many bytes - neither more nor less.
  653.  
  654. If you are REALLY interested in doing the right thing, you will 
  655. use the Communications Toolbox Connection Manager instead; this 
  656. will give you access to modems, direct lines, and networks of 
  657. various kinds using the same API! Great for stuff like BBSes 
  658. that may be on a network as well etc. The Comms Toolbox also 
  659. priovides modularized terminal emulat
  660.  
  661. ion and file transfer tools, although the Apple-suplied VT102 
  662. tool is pretty lame, as is the VT102 mode of the VT320 tool.
  663.  
  664. *3* TCP/IP and sockets
  665.  
  666. 3.1) Q: Where is a Berkley sockets library for the Mac?
  667.  
  668. A: There are some problems with that. MacTCP, the Mac Toolbox 
  669. implementation of TCP/IP, doesn't have an API that looks at all 
  670. like Berkley sockets. For instance, there is ONE paramater-block 
  671. call to do a combined listen()/accept()/bind() - sort of. I have 
  672. heard that there may be a socket library available by ftp from 
  673. MIT but haven't seen it myself.
  674.  
  675. There is also a pretty good C++ TCP implementation called GUSI 
  676. which is easily handled, and it also is callable from C using 
  677. the Berkley socket API. Apart from TCP, it also handles 
  678. "standard" Mac network protocols such as ADSP. The big 
  679. disadvantage is that it is currently only implemented for MPW. 
  680. The ftp site is nic.switch.ch, software/mac/src/mpw_c.
  681.  
  682. I can also recommend the Communications Toolbox; for the price 
  683. of using an API that is simpler than the Berkley sockets, you 
  684. get the benefit of being able to use any kind of connection (TCP 
  685. tools are available)
  686.  
  687. Novell and Wollogong offer commercial socket-like libraries.
  688.  
  689. 3.2) Q: Where do I find MacTCP?
  690.  
  691. A: You can buy the MacTCP developers kit from APDA. It is also 
  692. available on E T O, and if you want saner headers than those, 
  693. try ftp to seeding.apple.com.
  694.  
  695. *4* AppleEvents and the AppleEvent Object Model
  696.  
  697. 4.1) Q: What are AppleEvents?
  698.  
  699. A: AppleEvents are a level-5 network protocol. If you are not 
  700. familiar with the ISO network stack, this means it's a way of 
  701. structuring sessions between network entities (programs) that is 
  702. not dependent on the underlying protocol (such as PPC or TCP/IP) 
  703. Despite being a network protocol, they can be very useful on 
  704. Macs that are not on a network. In short, they provide 
  705. applications with a comprehensive way to send arbitrary 
  706. structured data to other applications (or themselves) which 
  707. receive the events through their main event loop.
  708.  
  709. The AppleEvent Object Model is a way of looking at applications 
  710. and the data they contain, and also a level-6 network protocol. 
  711. You _can_ send AppleEvent Object Model data through AppleEvents 
  712. (and the standard AppleEvents defined in the AppleEvent Registry 
  713. use it) but you don't have to - unless you want to talk with 
  714. other applications, of course, then the AEOM is a lingua franca.
  715.  
  716. 4.2) Q: What are the four required AppleEvents?
  717.  
  718. A: There are four events your application really must implement 
  719. if you want to sell it: the kCoreEventClass class, 
  720. kAEOpenApplication, kAEQuitApplication, kAEOpenDocuments and 
  721. kAEPrintDocuments events IDs. When you support these events (or 
  722. any AppleEvents) you will not get startup info through 
  723. GetAppParams() anymore, unless you run under System 6 of course.
  724.  
  725. The kAEOpenApplication event will be sent to you when the user 
  726. double-clicks your app and it's not started yet. When receiving 
  727. it, you can put up a new untitled window.
  728.  
  729. kAEOpenDocuments is sent when the user double-clicks your apps 
  730. documents. Note that if the first AppleEvent you receive is a 
  731. kAEOpenDocuments event, the user started your app by 
  732. double-clicking its documents. 
  733.  
  734. kAEPrintDocuments is sent when the user selects your documents 
  735. and chooses "Print" in the Finder menu. If this is the first 
  736. AppleEvent you receive, you should print the documents and then 
  737. quit the application again; if you received a kAEOpenApplication 
  738. or kAEOpenDocuments event before this, you should just print the 
  739. documents and close them when you're done.
  740.  
  741. kAEQuitApplication is sent to you when the user chooses 
  742. "Shutdown" or "Restart" from the Apple Menu. You should ask the 
  743. user wether he wants to save any unsaved changed documents, and 
  744. then quit unless the user presses Cancel.
  745.  
  746. Interestingly enough, you can use these four AppleEvents to send 
  747. even to non-AE-aware applications, and the system will translate 
  748. these events into fake menu selections for you.
  749.  
  750. A good way of shutting down the Finder is to send it a Quit 
  751. AppleEvent. You should send a Quit AppleEvent to File Sharing 
  752. Extension before you shut down the Finder, though; the FSE is 
  753. found by looking for a process with the creator 'hhgg'.
  754.  
  755. 4.3) Q: Are there any limits or tradeoffs with AppleEvents?
  756.  
  757. A: As always, more power means more responsibility.
  758.  
  759. AppleEvents sent to applications on other Macs require 
  760. authentification the first time they are sent. If the remote Mac 
  761. allows Guests to link to programs, the INIT AutoGuest 2.0 might 
  762. help (or the code solution that comes with it and you can build 
  763. into your application)
  764.  
  765. In the first version of the AppleEvent manager, there was a 
  766. total 64K limit on the size of data and overhead. This limit has 
  767. been lifted with the version of the AppleEvent manager that 
  768. comes with AppleScript. 
  769.  
  770. AppleEvents require a lot of memory copying and handle resizing 
  771. in their construction; this means that large AppleEvents may be 
  772. slow in construction, especially when compared to a pure PPC 
  773. Toolbox or ADSP/ASDSP link. 
  774.  
  775. You should use your own application signature as event class for 
  776. AppleEvents you make up, in order not to collide with anybody 
  777. else. Other than that, you are free to make your own events for 
  778. your own needs, though supporting the required events and at 
  779. least a subset of the Core event suite will buy you a lot of 
  780. functinality from within AppleScript. Especially important are 
  781. the Get Current Selection and Set Current Selection events 
  782. (which are really Get/Set Data on the contents of the current 
  783. selection of the application)
  784.  
  785. The signature for your application SHOULD be registered with DTS 
  786. to avoid conflicts; this is done through e-mail to 
  787. DEVSUPPORT@AppleLink.Apple.Com and the form you use is located 
  788. on the developer CDs and found on ftp.apple.com.
  789.  
  790. *5* AppleScript
  791.  
  792. 5.1) Q: How does AppleEvents interface with AppleScript?
  793.  
  794. A: AppleEvents are the meat and potatoes of AppleScript. If you 
  795. support the AppleEvent Object Model from within your 
  796. application, users can control you through AppleScript.
  797.  
  798. The first thing you should do is get ahold of Inside Mac: 
  799. Interapplication Communication, and a copy of the AppleEvents 
  800. Registry. The former tells you all you ever need to know about 
  801. AppleEvents, while the latter is paramount for implementing the 
  802. right standard events. If everybody use the standard events, 
  803. dynamic data interchange between any applications will become 
  804. sweet reality!
  805.  
  806. Then there is the 'aete' resource which lets you put names on 
  807. the events you support, so that users can "Open Terminology" on 
  808. your application from within the Apple Script Editor and use the 
  809. proper AppleScript commands in their scripts. The format of an 
  810. aete resource is defined in Inside Macintosh: Interapplication 
  811. Communication.
  812.  
  813. 5.2) Q: Can I compile and run scripts from within my 
  814. application?
  815.  
  816. A: Yes, this is very simple. There are toolbox calls for reading 
  817. scripts, compiling scripts, and executing scripts. (OSACompile, 
  818. OSAExecute) These are all documented in Inside Mac: 
  819. Interapplication Communication.
  820.  
  821. 5.3) Q: Is this a good way of getting a macro language almost 
  822. for free?
  823.  
  824. A: "Good" is an understatement. Just let users write scripts, 
  825. load them into menu items and go. Total systems integration in 
  826. under a week, including adding support for the AEOM to your 
  827. application.
  828.  
  829. There is source code for an application called "MenuScipter" on 
  830. the developer CD which shows you how to do an application with 
  831. all of the menus being AppleScript scripts.
  832.  
  833. *6* Drawing using QuickDraw
  834.  
  835. 6.1) Q: Why is CopyBits so slow?
  836.  
  837. A: It is not. It just requires some hand-holding to get good 
  838. results. The main rules are: Make sure the source and 
  839. destination pixMaps are of the same depth.
  840.  
  841. Make sure the front color is black and the back color is white.
  842.  
  843. Use srcCopy and don't use a masking region.
  844.  
  845. Copy to an unclipped window (the frontmost window).
  846.  
  847. Make sure the ctSeed values of the source pixMap and dest pixMap 
  848. match.
  849.  
  850. Copying few and large pixMaps is faster than copying many and 
  851. small ones. Icon-sized sprites count as small ones. 
  852.  
  853. Make sure your source bitmap or pixelMap has the same alignment, 
  854. when adjusted for the source and destination rect expressed in 
  855. global screen coordinates. The necessary alignment is 32 bits (4 
  856. bytes), although 128 bit (16 byte) alignment is probably even 
  857. better on 68040 macs and won't hurt on other macs.
  858.  
  859. Example of global alignment:
  860.  
  861. Your window is positioned at (42,100) (H,V) 
  862.  
  863. Your destination rectangle is (10,20)-(74,52)
  864.  
  865. The alignment coefficient of the rectangle in global coordinates 
  866. is (42+10)*bitDepth where bitDepth is one of 1,2,4,8,16 or 32.
  867.  
  868. Make sure your source pixmap rect has the same coeffecient 
  869. modulo your alignment factor (in bits) For black&white macs, 
  870. this is still true, although bitDepth is fix at 1. Offscreen 
  871. pixMaps can calculate with a "global posistion" of 0,0 and get 
  872. correct results.
  873.  
  874. 6.2) Q: Why is CopyBits still too slow?
  875.  
  876. A: Because there is always some overhead involved in calling 
  877. QuickDraw; you have the trap dispatcher, clipping checks, and 
  878. checking wether the CopyBits call is being recorded in a PICT 
  879. handle (if you called OpenPicture) 
  880.  
  881. If you can't live with this, look at *7* below, but PLEASE try 
  882. and make CopyBits work, and retain the CopyBits code in your 
  883. application, so users with special monitors (accellerator cards, 
  884. PowerBook color screens, Radius Pivot screens) can still play 
  885. your game. (non-game applications don't need more speed than 
  886. CopyBits can give at its max. Promise!)
  887.  
  888. 6.3) Q: What is the fastest way to set one pixel?
  889.  
  890. A: NOT SetCPixel()! Assuming you have the correct ForeColor() 
  891. set, you can set the pen size to (1,0) and call Line (0,1)
  892.  
  893. I have heard PaintRect is good for this but requires slightly 
  894. more code.  Using PaintRect eliminates a trap call.
  895.  
  896. 6.4) Q: Why do pictures I record suddenly draw as empty space or 
  897. not draw at all?
  898.  
  899. A: When recording pictures, you have to set the clipping area to 
  900. exactly the frame of the picture you are recording. This is 
  901. because it is initally set at -32768,32727 in both directions, 
  902. and offsetting the picture even one pixel when drawing it will 
  903. result in the region wrapping around and becoming empty.
  904.  
  905. When recording pictures, do this:
  906.  
  907. *code*
  908. PicHandle h = OpenPicture ( & theRect ) ; ClipRect ( & theRect ) ;
  909.     /* draw the picture */
  910.     ClosePicture ( ) ;
  911. *end*
  912.  
  913. 6.5) Q: Where can I find the format of picture files and 
  914. resources?
  915.  
  916. A: The format of a picture resource version 1 is defined in a 
  917. technical note. This format is obsolete.
  918.  
  919. The format of a picture resource version 2 is defined in Old 
  920. Inside Mac vol V, with addenda in Old Inside Mac vol VI.
  921.  
  922. Some things happen with QuickTime compressed pictures; try the 
  923. Inside Mac: QuickTime book or wait for Inside Mac: Imaging which 
  924. is the definite reference on QuickDraw.
  925.  
  926. The format of a picture file is the same as that of a picture 
  927. resource with 512 added 0 bytes in front.
  928.  
  929. 6.6) Q: GWorlds?
  930.  
  931. A: What about them? They're great. Look them up in Old Inside 
  932. Mac vol VI. Don't forget to SetGWorld back to what it was before 
  933. calling WaitNextEvent.
  934.  
  935. 6.7) Q: How do I find the current depth of the screen?
  936.  
  937. A: My question to you is: What screen? Many macs have more than 
  938. one screen attached. You can use GetDeviceList and walk the 
  939. devices to find the screen you're looking for (use 
  940. TestDeviceAttrib to see wether it's a screen) or you can call 
  941. GetMaxDevice() to find the deepest device your window 
  942. intersects.
  943.  
  944. Once you have the device handle, finding the depth is just a 
  945. matter of looking at the dgPMap pixMapHandle, and dereference it 
  946. to the pmSize field. Done.
  947.  
  948. *7* Drawing directly to screen
  949.  
  950. 7.1) Q: Why is it a bad idea to draw directly to screen?
  951.  
  952. A: Because of several reasons:
  953.  
  954. - You will be incompatible with future display hardware.
  955.  
  956. - You will be incompatible with some present-day display 
  957. hardware, such as Radius Pivots and PowerBook color screens.
  958.  
  959. - You have to think about a lot of things; testing it all on 
  960. your own machine is not possible and the chances of crashing are 
  961. great.
  962.  
  963. - You will be incompatible with future hardware where devices 
  964. may live in some unaccessible I/O space.
  965.  
  966. 7.2) Q: But I really need to do it. I can't make my animation 
  967. into a QuickTime movie, and CopyBits is too slow, even when 
  968. syncing to the screen retrace.
  969.  
  970. A: You have to prepare yourself, and ask these questions:
  971.  
  972. 1) Do I want to support all screens, or just 8-bit devices?
  973.  
  974. 2) Do I have a few weeks of free time to make it work?
  975.  
  976. 3) Do I want to get nasty mail when I break on some hardware and 
  977. have to rev the application - even if I may not be able to get 
  978. ahold of the hardware that makes it break?
  979.  
  980. If all you're doing is rendering an image pixel-by-pixel or 
  981. line-by-line, maybe you can draw directly into an offscreen 
  982. pixMap/GWorld and then CopyBits the entire GWorld to screen? 
  983. That will be more compatible, especially if you use the 
  984. keepLocal flag when creating the GWorld.
  985.  
  986. 7.3) Q: Okay, so how do I get the base address of the screen?
  987.  
  988. A: "The" screen? Which screen? There may be several. The base 
  989. address may be on an accellerated screen card. There may be more 
  990. than one screen covering the same desktop area.
  991.  
  992. Due to unfortunate circumstances, there is a bug in 
  993. GetPixBaseAddr() that causes it to return incorrect results for 
  994. some versions of System 7. Instead, get the baseAddr directly 
  995. >from the gdPMap handle of the GDHandle for the screen you draw 
  996. to. This address may need switching to 32bit mode to be valid.
  997.  
  998. 7.4) Q: Quit stalling and give me code!
  999.  
  1000. A: Okay, but I'll let you sweat over Inside Mac to figure out 
  1001. what it does. All of it is important; believe me! To make this 
  1002. code run faster, a lot of the things it does can be done once 
  1003. before starting to draw.
  1004.  
  1005. Make sure that you have a window that covers the area where you 
  1006. are drawing, so other windows will not be overdrawn. Also make 
  1007. sure that you do not do direct-to-screen-drawing while you are 
  1008. in the background.
  1009.  
  1010. *code*
  1011. /* This is presently untested code */
  1012. /* value is dependent on what depth the screen has */
  1013. /* this code doesn't work on non-color-quickdraw Macs (i e the MacClassic) */
  1014. /* where is in GLOBAL coordinates */
  1015. void
  1016. SetPixel ( Point where , unsigned long value ) {
  1017. Rect r ;
  1018. GDHandle theGD ;
  1019. char * ptr ;
  1020. long rowBytes ;
  1021. short bitsPerPixel ;
  1022. PixMapHandle pmh ;
  1023. Boolean oldMode ;
  1024.     r . left = where . h ;
  1025.     r . top = where    . v ;
  1026.     r . right = r . left + 1 ;
  1027. r . bottom = r . top + 1 ;
  1028.     theGD = GetMaxDevice ( & r ) ;
  1029.     if ( theGD ) {
  1030. where . v -= ( * theGD ) -> gdRect . left ; where . h -= ( * theGD ) -> gdRect . top ; pmh = ( * theGD ) -> gdPMap ;
  1031. rowBytes = ( ( * pmh ) -> rowBytes ) & 0x3fff ; ptr = ( char * ) ( * pmh ) -> baseAddr ; bitsPerPixel = ( * pmh ) -> pixelSize ; oldMode = true32b ;
  1032.         ptr += where . v * rowBytes ;
  1033. SwapMMUMode ( & oldMode ) ; switch ( bitsPerPixel ) { case 1 :
  1034. if ( value & 1 ) { 
  1035. ptr [ where . h >> 3 ] |= ( 128 >> ( where . h & 7 ) ) ;
  1036.             } else {
  1037.                 ptr [ where . h >> 3 ] &= ~( 128 >> ( where . h & 7 ) ) ;
  1038.             }
  1039.             break ;
  1040.         case 2 :
  1041.             ptr [ where . h >> 2 ] &= ( 192 >> 2 * ( where . h & 3 ) ) ;
  1042. ptr [ where . h >> 2 ] |= ( value & 3 ) << 2 * ( 3 - ( where . h & 3 ) ) ; break ;
  1043.         case 4 :
  1044.             ptr [ where . h >> 1 ] &= ( where . h & 1 ) ? 0xf : 0xf0 ;
  1045. ptr [ where . h >> 1 ] |= ( value & 15 ) << 4 * ( 1 - ( where . h & 1 ) ) ; break ;
  1046.         case 8 :
  1047.             ptr [ where . h ] = value ;
  1048.             break ;
  1049.         case 16 :
  1050. ( ( unsigned short * ) ptr ) [ where . h ] = value ;
  1051.             break ;
  1052.         case 32 :
  1053. ( ( unsigned long * ) ptr ) [ where . h ] = value ;
  1054.             break ;
  1055.         }
  1056.         SwapMMUMode ( & oldMode ) ;
  1057.     }
  1058. }
  1059. *end*
  1060.  
  1061. *8* Cache issues and other processor differences
  1062.  
  1063. 8.1) Q: Why does my application work on an SE with accellerator 
  1064. (or a Mac II or Quadra), but not on one without?
  1065.  
  1066. A: Assuming you're not calling Color QuickDraw (which is not 
  1067. available on accellerated SEs), you most probably have an 
  1068. odd-aligned word access somewhere. 
  1069.  
  1070. The 68000 does not allow words or longwords to be read from odd 
  1071. addresses, while the 68020 and up relaxes this restriction (it 
  1072. still is slower than aligned-word access though)
  1073.  
  1074. This may or may not crash depending on your compiler:
  1075.  
  1076. *code*
  1077. struct foo {
  1078.     char c1 ;
  1079.     char c2 ;
  1080.     char c3 ;
  1081.     char c4 ;
  1082.     char c5 ;
  1083. } bar ;
  1084.     long * x = ( long * ) & bar . c2 ;
  1085.     * x = 0x12345678 ; /* X is odd if compiler doesn't pad */
  1086. This WILL crash on an SE/Plus/Classic/PB100:
  1087. char foo [ 10 ] ;
  1088.     long * x = ( long * ) & foo [ 1 ] ;
  1089.     * x = 0x12345678 ;
  1090. *end*
  1091.  
  1092. 8.2) Q: Why does my application work on a IIci but not on a 
  1093. Quadra?
  1094.  
  1095. A: Two reasons:
  1096.  
  1097. 1) The Quadras 900 and 950 have special processors that handle 
  1098. the serial ports; if you write directly to the serial chips, you 
  1099. will crash (this goes for the IIfx as well)
  1100.  
  1101. 2) The Quadras have 68040 processors, as have the Centrises. 
  1102. These processors have separate instruction and data caches (like 
  1103. the 68030) but they are larger (4K each) and unlike the 68030 
  1104. which is write-through data cached, the 68040 is copy-back data 
  1105. cached. This means that changes you make to "your code" aren't 
  1106. really changed all the time, since the changes may still be in 
  1107. the data cache and not written to memory when the CPU reads that 
  1108. part of memory into its I-cache. Even worse; that part might 
  1109. already have been read into the I-cache before you change it in 
  1110. the D-cache, meaning that writing out the D-cache will still not 
  1111. be enough. You need to flush both the caches when writing 
  1112. self-modifying code.
  1113.  
  1114. Self-modifying code includes code that builds its own jump 
  1115. tables and code that decrypts itself and code that "stubs" MDEFs 
  1116. or WDEFs to jump back into the application code.
  1117.  
  1118. You flush the cache using FlushDataCache() which is implemented 
  1119. if Gestalt says you have a 68020 or better processor (or if the 
  1120. _HwDispatch trap is implemented)
  1121.  
  1122. 8.3) Q: Why does my application work on my Quadra but not on my 
  1123. accellerated SE?
  1124.  
  1125. A: You're probably calling Color QuickDraw without first 
  1126. checking if it's available. The following machines do not have 
  1127. color QuickDraw in ROM nor RAM:
  1128.  
  1129. Mac Plus, Mac SE, Mac Classic, Mac Luggable, PowerBook 100, 
  1130. Outbound
  1131.  
  1132. 8.4) Q: I do check for color quickdraw, but crash nevertheless.
  1133.  
  1134. A: _Gestalt lies under some versions of System 7; it says that 
  1135. non-color machines HAVE color QuickDraw when you test using the 
  1136. gestaltQuickdrawFeatures selector.
  1137.  
  1138. Instead, check the gestaltQuickdrawVersion selector, if it 
  1139. returns >= gestalt8BitQuickdraw then you can safely use 
  1140. gestaltQuickdrawFeatures, else you only have b/w QuickDraw.
  1141.  
  1142. 8.5) Q: Why are there no compilers that optimize for the 
  1143. Mc68040?
  1144.  
  1145. A: Beats me; optimizing for the 68040 can make programs up to 
  1146. 50% faster on that chip while still losing nothing, or very 
  1147. little (less than 10%) on older chips.
  1148.  
  1149. *9* Inflammatory subjects
  1150.  
  1151. 9.1) Q: What about pre-emptive multitasking?
  1152.  
  1153. A: To the user, the Mac multitasking method, which builds upon 
  1154. each application calling WaitNextEvent, GetNextEvent or 
  1155. EventAvail every so often and the Process Manager/MultiFinder 
  1156. switching applications only at such calls, is at least as good 
  1157. as preemtive multitasking, because the present system 
  1158. priotitizes user interface responsiveness over everything else. 
  1159. The only shortfall about this is formatting floppies, which 
  1160. locks up the Mac CPU. This is because the Mac floppy controller 
  1161. is really stupid, and would happen even if the Mac multitasked 
  1162. preemptively.
  1163.  
  1164. There IS "real" pre-emptive multitasking available for use in 
  1165. Mac applications; the expensive way is buying A/UX 3.0 which can 
  1166. have Mac applications written as UNIX processes; the cheap way 
  1167. is installing the Thread Manager which will allow you to create 
  1168. pre-emptive threads. However, the restrictions on those threads 
  1169. are the same as those on Time Manager tasks: don't call any 
  1170. function in an unloaded segment, and don't call QuickDraw or any 
  1171. toolbox call which may move memory (which are most ToolBox 
  1172. calls; paradoxally, BlockMove is safe :-) as are, surprisingly, 
  1173. FSRead and FSWrite)
  1174.  
  1175. There are several problems with making the Mac OS preemptive; 
  1176. including apps that draw outside their windows or directly to 
  1177. screen, user dragging and other issues.
  1178.  
  1179. 9.2) Q: What about protected memory? I'm sick and tired of 
  1180. re-booting when my application crashes.
  1181.  
  1182. A: Write better software!
  1183.  
  1184. Or install The Debugger from Jasik Designs, which can provide 
  1185. your application with write-protection of critical parts of 
  1186. memory. This may only work for 030 Macs, though; I'm not clear 
  1187. as to wether it's implemented for 040 Macs.
  1188.  
  1189. Making the Mac OS memory-protected is tricky, because 
  1190. applications expect to be able to write to low memory, the 
  1191. system heap, temporary memory, window lists, and even each 
  1192. other's heaps in some interapplication communication solutions 
  1193. that date back to before AppleEvents and the PPC Toolbox.
  1194.  
  1195. *10* Handles; they are driving me crazy
  1196.  
  1197. 10.1) Q: What is a handle?
  1198.  
  1199. A: A handle is a pointer to a pointer to something. However, it 
  1200. is more than that; creating a handle by taking the address of 
  1201. one of your own pointers does NOT create a Handle; the Memory 
  1202. Manager will only deal properly with Handles that are created 
  1203. using NewHandle or something that calls it (such as NewRgn or 
  1204. GetResource)
  1205.  
  1206. 10.2) Q: When do I have to lock a Handle?
  1207.  
  1208. A: The contents of a Handle may move, and when it does, the 
  1209. pointer your handle is pointing to is changed to point to the 
  1210. new address so your handle is always valid. The toolbox may call 
  1211. the memory manager to allocate more memory pretty much anytime 
  1212.  
  1213. you call it (the toolbox) and when memory is allocated, your 
  1214. handle may move in memory. Don't dereference a handle into a 
  1215. pointer (or take the address of a field in a record a handle is 
  1216. double-pointing to) and then call the toolbox and expect the 
  1217. pointer to still be valid. The only way to ensure that the 
  1218. pointer will still be valid is to call HLock on the handle to 
  1219. lock it.
  1220.  
  1221. Use HGetState and HSetState to save & restore the "locked" state 
  1222. of a handle when you lock it.
  1223.  
  1224. 10.3) Q: How do I dispose of Handles?
  1225.  
  1226. A: DisposeHandle (formerly called DisposHandle) once and ONLY 
  1227. once will do the trick. Trying to dispose of an already disposed 
  1228. Handle is an error. DoubleTrouble (see above) will catch such 
  1229. bugs when they do occur.
  1230.  
  1231. 10.4) Q: What about resources?
  1232.  
  1233. A: Calling GetResource returns NULL if the resource is not found 
  1234. or there is not enough memory, else it returns a handle to the 
  1235. resource. This handle may be moved or locked like any other 
  1236. handle, but DO NOT call DisposeHandle to get rid of a resource 
  1237. handle - call ReleaseResource. DisposeResource (see above) will 
  1238. catch this kind of bug.
  1239.  
  1240. Remember that AddResource makes a resource handle out of an 
  1241. ordinary handle, and RmveResource or DetachResource makes an 
  1242. ordinary handle out of a resource handle. You cannot call 
  1243. AddResource with a resource handle; you have to DetachResource 
  1244. it first.
  1245.  
  1246. Resource handles are automagically disposed when the resource 
  1247. file they belong to is closed.
  1248.  
  1249. 10.5) Q: I'm trying to use a largish array in Think C, but get a 
  1250. "code overflow" error. This is valid C, why doesn't it work?
  1251.  
  1252. A: The ANSI standard does not guarantee that any structure 
  1253. larger than 32767 bytes be correctly handled. Because of 
  1254. historical constraints, the Mac memory model is built around 
  1255. several small blocks of size 32K or less; these are used both 
  1256. for code and global/static data. If you want to use more code or 
  1257. data, you have to turn on "far code" or "far data" - you still 
  1258. will not get around the restriction of 32K code or data per 
  1259. compiled file, though.
  1260.  
  1261. As opposed to, say, DOS or Windows, however, you can allocate as 
  1262. much memory as you want (and there is in the machine) and step 
  1263. through it using ordinary pointers; it's just that global and 
  1264. static data space is addressed off the A5 register using a 16bit 
  1265. displacement addressing mode in the 68000 processor.
  1266.  
  1267. *11* _Gestalt and compatibility
  1268.  
  1269. 11.1) Q: I see all these people call Gestalt without first 
  1270. checking wether it's implemented. Isn't that bad?
  1271.  
  1272. A: No; Gestalt and a few other traps (the HXxx file manager 
  1273. traps, and FindFolder) are implemented using glue so they do the 
  1274. right thing even if the trap is not implemented.
  1275.  
  1276. If you want to get rid of the glue, you can #define 
  1277. SystemSevenOrLater (and, using Think C/C++, re-pre-compile 
  1278. MacHeaders) However, then you will be responsible for checking 
  1279. for these features before you use them.
  1280.  
  1281. 11.2) Q: What more functions are implemented in glue?
  1282.  
  1283. A: Wake Up and Smell the Glue! [by Matthias Neeracher]
  1284.  
  1285. How often have you wished you could use that cool new ToolBox 
  1286. call, but didn't want to make your application System 7 
  1287. dependent? Well, it might be that you *could* in fact have used 
  1288. the call. Several traps are implemented in glue, that is, much 
  1289. of their functionality is linked into your application and thus 
  1290. available even if you are running under an old System.
  1291.  
  1292. This list applies to MPW 3.2 and should also be valid for the 
  1293. current version of Think C. If you find any inaccuracies, please 
  1294. report them to me. (neeri@iis.ee.ethz.ch)
  1295.  
  1296. FSOpen: Tries first OpenDF, then Open.
  1297.  
  1298. HOpenResFile: Full functionality emulated if trap not available
  1299.  
  1300. HCreateResFile: Full functionality emulated if trap not 
  1301. available
  1302.  
  1303. FindFolder: Under System 6, understands the following values for 
  1304. folderType and returns the System Folder for all of them:
  1305.  
  1306. kAppleMenuFolderType
  1307.  
  1308. kControlPanelFolderType
  1309.  
  1310. kExtensionFolderType
  1311.  
  1312. kPreferencesFolderType
  1313.  
  1314. kPrintMonitorDocsFolderType
  1315.  
  1316. kStartupFolderType
  1317.  
  1318. kSystemFolderType
  1319.  
  1320. kTemporaryFolderType
  1321.  
  1322. SysEnvirons: Full functionality emulated if trap not available
  1323.  
  1324. NewGestalt: Returns an error if not implemented
  1325.  
  1326. ReplaceGestalt: Returns an error if not implemented
  1327.  
  1328. Gestalt: The following selectors are always implemented:
  1329.  
  1330. vers    mach    sysv    proc    fpu     
  1331.  
  1332. qd      kbd     atlk    ram     lram    
  1333.  
  1334. 11.3) Q: I have to support System 6, don't I?
  1335.  
  1336. A: It would be foolish to lock yourself out of the many benefits 
  1337. the System 7 API provides for software that you start to write 
  1338. now. Some of the System 6 and older things (likely SFGetFile and 
  1339. wdRefNums among others) will be phased out of the interfaces and 
  1340. lose support; especially on future platforms.
  1341.  
  1342. The installed base of System 7 is larger than that of System 6; 
  1343. this is not surprising because Apple has been shipping System 7 
  1344. for several years with all new machines, including the LCII, 
  1345. Classic II, Performas and Color Classic. Another argument is 
  1346. that newer computer owners (having System 7) are much more 
  1347. likely to buy new software than old computer owners who have 
  1348. systems that already do what they want them to.
  1349.  
  1350. The added work to support both System 6 and System 7 is 
  1351. significant; if you have the time and money you may want to do 
  1352. it, but only supporting System 6 and not System 7 is doomed to 
  1353. fail in the market of today.
  1354.  
  1355. Some may call this position subjective; I call it business sense 
  1356. based on market demographics. A rule of thumb may be that if you 
  1357. target color machines only, you can just as well demand System 7 
  1358. as well.
  1359.  
  1360. *12* Standalone code and dynamic linking
  1361.  
  1362. 12.1) Q: I've got a CODE resource off in limboland (sometimes 
  1363. called the resource fork) and I want to open it... what do I do?
  1364.  
  1365. A: You open the file you have the code resource in, load the 
  1366. resource and lock it high (don't unlock it first, since someone 
  1367. else may be using it). Then you cast the handle to a function 
  1368. pointer, and call it normally.
  1369.  
  1370. Suppose your code resource is compiled as a SACD id 128, and is 
  1371. defined as:
  1372.  
  1373. *code*
  1374. long
  1375. main ( MyParams * params ) {
  1376.     switch ( params -> message ) {
  1377.     case messageInit :
  1378.         return init ( params ) ;
  1379.     ...
  1380.     }
  1381.     return 0L ;
  1382. }
  1383. *end*
  1384.  
  1385. Also suppose you already have the vRefNum, parID and name of the 
  1386. resource file you want to use. Do this:
  1387.  
  1388. *code*
  1389.     setup_paramblock ( & the_params ) ;
  1390.     the_params . message = messageInit ;
  1391.     refNum = HOpenResFile ( vRefNum , parID , name , fsRdPerm ) ;
  1392.     if ( refNum < 1 ) {
  1393.         fail ( ResError ( ) ) ;
  1394.     }
  1395.     the_code = GetResource ( 'SACD' , 128 ) ;
  1396.     HLockHi ( the_code ) ;
  1397.     retval = ( * ( ( long ( * ) ( MyParams * ) ) * the_code ) ) ( & the_params ) ;
  1398.     ...
  1399. *end*
  1400.  
  1401. Exactly how you structure your calling conventions is up to you; 
  1402. there is no accepted standard (except for HyperCard XCMDs, but 
  1403. that is probably overkill for you).
  1404.  
  1405. *13*
  1406.  
  1407. 13.1) Q: How do I read the modifier keys of the keyboard?
  1408.  
  1409. A: Just call EventAvail and check the event.modifiers field. 
  1410. Only works when you are in the foreground. You can also use 
  1411. GetKeys(), or (as a last resort) check the lo-mem global KeyMap 
  1412. directly.
  1413.  
  1414. *14* QuickTime
  1415.  
  1416. 14.1) Q: I want to write a Amiga QuickTime player and need the 
  1417. CODEC format details.
  1418.  
  1419. A: Although the structure of QuickTime movies is well documented 
  1420. in Inside Mac: QuickTime, the inner workings of the Apple 
  1421. compression modules is a trade secret that Apple will only 
  1422. license to you at great cost. Perhaps it's time for a freeware, 
  1423. cross-platform QuickTime codec?
  1424.  
  1425. *15* Ice Cream and Frozen Yoghurt
  1426.  
  1427. 15.1) Q: Dessert?
  1428.  
  1429. A: Honey Hill Farms Cookie Jar Frozen Yoghurt or Haagen-Dazs 
  1430. Raspberry & Cream Ice Cream.
  1431.  
  1432. -- 
  1433.  -- Jon W{tte, h+@nada.kth.se, Mac Hacker Deluxe --
  1434.     Hackers push all the right buttons.
  1435.  
  1436.